package br.com.sig.security;

import java.io.Serializable;

import javax.inject.Inject;
import javax.inject.Named;

import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.CredentialsImpl;
import org.picketlink.idm.impl.api.model.SimpleUser;

import br.com.sig.business.exception.BaseException;
import br.com.sig.security.business.model.bo.UserBO;
import br.com.sig.security.business.model.entity.User;

@Named
public class BaseAuthenticator extends org.jboss.seam.security.BaseAuthenticator implements Serializable {

	private static final long serialVersionUID = 29679855740916858L;

	@Inject 
	private Credentials credentials;
	
	@Inject
	private UserBO userBO;
	
	private User user;

	@Override
	public void authenticate() {
		
		try {
			
			if (credentials.getUsername() == null) {
				setStatus(AuthenticationStatus.FAILURE);
			} else {
				user = userBO.findByUserName(credentials.getUsername());
				
				if (user.getPassword().equals(((CredentialsImpl)credentials).getPassword())) {
					setStatus(AuthenticationStatus.SUCCESS);
					setUser(new SimpleUser(user.getUserName()));
				} else {
					setStatus(AuthenticationStatus.FAILURE);
				}
			}
		} catch (IndexOutOfBoundsException | BaseException e) {
			e.printStackTrace();
			setStatus(AuthenticationStatus.FAILURE);
		}

	}

}